package com.qingluan.dd;

import java.io.File;
import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.qingluan.DataFormat.MissionTag;
import com.qingluan.Database.MissionDataBase;
import com.qingluan.Database.Personal_Info_database;
import com.qingluan.Database.TempDataBase;
import com.qingluan.arguments.ARGUMENTS;
import com.qingluan.dd.InetTool.BitmapDownloader;
import com.qingluan.dd.InetTool.BitmapDownloader.CallBack;
import com.qingluan.dd.InetTool.IndexInitializationInfo;
import com.qingluan.dd.InetTool.IndexInitializationInfo.setOnRefreshInfo;
import com.qingluan.dd.InetTool.IndexInitializationInfo.setRefreshInfo;
import com.qingluan.dd.util.FileCache;
import com.qingluan.dd.util.SystemUiHider;
import com.qingluan.server.BroadCastRecevier;
import com.qingluan.server.BroadCastRecevier.ReceiveListener;
import com.qingluan.widget.BitmapHelper;
import com.qingluan.widget.DragListView;
import com.qingluan.widget.BitmapHelper.onBitmapLoaded;
import com.qingluan.widget.DragListView.OnRefreshListener;
import com.qingluan.widget.DragListView.OnRefreshTailListener;
import com.qingluan.widget.DragListViewAdapter;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.DragEvent;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnDragListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class IndexFullscreenActivity extends Activity {
	/**
	 * Whether or not the system UI should be auto-hidden after
	 * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
	 */
	private static final boolean AUTO_HIDE = true;

	/**
	 * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
	 * user interaction before hiding the system UI.
	 */
	private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

	/**
	 * If set, will toggle the system UI visibility upon interaction. Otherwise,
	 * will show the system UI visibility upon interaction.
	 */
	private static final boolean TOGGLE_ON_CLICK = true;

	/**
	 * The flags to pass to {@link SystemUiHider#getInstance}.
	 */
	private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;

	/**
	 * The instance of the {@link SystemUiHider} for this activity.
	 */
	private SystemUiHider mSystemUiHider;
	//child ui components
	private DragListViewAdapter  adapter;
	private DragListView TaskList;
	private String uid;
	private Context context_this;
	private String TAG = IndexFullscreenActivity.class.getName();
	//web arguments
	String URL = ARGUMENTS.INDEX_IP;
	//context area
	private BroadCastRecevier broadCast;
	public int FROM_MISSION_LIST = 10000;
	
	//token area
	private String token_id;
	private String token_key;
	
	//log argu area
	private static String tag = IndexFullscreenActivity.class.getName();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_index_fullscreen);
		/*
		 * get uid from intent ..
		 * 
		 */
		uid = getIntent().getExtras().getString("uid");
		token_id = getIntent().getExtras().getString("token_id");
		token_key = getIntent().getExtras().getString("token_key");
		Log.d(tag, "token id : "+ token_id+" key:"+token_key);
		
		context_this = getApplicationContext();
		final View controlsView = findViewById(R.id.fullscreen_content_controls);
		final View contentView = findViewById(R.id.fullscreen_content);

		// Set up an instance of SystemUiHider to control the system UI for
		// this activity.
		mSystemUiHider = SystemUiHider.getInstance(this, contentView,
				HIDER_FLAGS);
		mSystemUiHider.setup();
		mSystemUiHider
				.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
					// Cached values.
					int mControlsHeight;
					int mShortAnimTime;

					@Override
					@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
					public void onVisibilityChange(boolean visible) {
						if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
							// If the ViewPropertyAnimator API is available
							// (Honeycomb MR2 and later), use it to animate the
							// in-layout UI controls at the bottom of the
							// screen.
							if (mControlsHeight == 0) {
								mControlsHeight = controlsView.getHeight();
							}
							if (mShortAnimTime == 0) {
								mShortAnimTime = getResources().getInteger(
										android.R.integer.config_shortAnimTime);
							}
							controlsView
									.animate()
									.translationY(visible ? 0 : mControlsHeight)
									.setDuration(mShortAnimTime);
						} else {
							// If the ViewPropertyAnimator APIs aren't
							// available, simply show or hide the in-layout UI
							// controls.
							controlsView.setVisibility(visible ? View.VISIBLE
									: View.GONE);
						}

						if (visible && AUTO_HIDE) {
							// Schedule a hide().
							delayedHide(AUTO_HIDE_DELAY_MILLIS);
						}
					}
				});

		// Set up the user interaction to manually show or hide the system UI.
		contentView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (TOGGLE_ON_CLICK) {
					mSystemUiHider.toggle();
				} else {
					mSystemUiHider.show();
				}
			}
		});
		TaskList = (DragListView)findViewById(R.id.New_Mission);
		adapter = new  DragListViewAdapter(this);
				// Upon interacting with UI controls, delay any scheduled hide()
		// operations to prevent the jarring behavior of controls going away
		// while interacting with the UI.

		findViewById(R.id.Mission_info).setOnTouchListener(
				mDelayHideTouchListener);

		findViewById(R.id.Map_model).setOnTouchListener(
				mDelayHideTouchListener);

		findViewById(R.id.Create_miss).setOnTouchListener(
				mDelayHideTouchListener);
		
		/**#######################
		 *  all internet work initialization 
		 */
		Initialization();
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.d("App", "on Resume");
		super.onResume();
		if (broadCast != null){
			broadCast.setReceiveListenr(new ReceiveListener(){

				@Override
				public void receive(String info) {
					// TODO Auto-generated method stub
					boolean res  = adapter.removeItemByObj(info);
					if (res){
						Log.d("delete", "remove ok");
					}
				}
				
			});
		}
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		unregisterReceiver(broadCast);
		super.onDestroy();
	}
//	@Override
//	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//		// TODO Auto-generated method stub
//		
//	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK){
			new AlertDialog.Builder(IndexFullscreenActivity.this)
				.setTitle("Exit")
				.setMessage("Sure to exit ?")
				.setPositiveButton("ok",  new DialogInterface.OnClickListener(){

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
//						android.os.Process.killProcess(android.os.Process.myPid());
//						System.exit(0);
						IndexFullscreenActivity.this.finish();
					}
					
				}).show();
		}
		return false;
	}
	
	/*
	 *非系统部分初始化的操作 
	 */
	public void Initialization(){
		IntentFilter filter = new IntentFilter();
		broadCast = new BroadCastRecevier();
		filter.addAction(ARGUMENTS.SEND_INFO_TO_SERVICE);
		registerReceiver(broadCast, filter);
		Log.d("indexFullscreenActivity","register broadcast");
		adapter.getMission();
		TaskList.setAdapter(adapter);
		
		TaskList.setOnRefreshListener(new OnRefreshListener(){

			@Override
			public int onRefresh() {
				// TODO Auto-generated method stub
						// TODO Auto-generated method stub
				
				new IndexInitializationInfo(uid,context_this).RefershInfoPost(URL
						,adapter 
						,new setRefreshInfo(){

						@Override
						public void RefreshView(String result) {
							// TODO Auto-generated method stub
							//do some
							JSONObject AllResults = null;
							try {
								AllResults = new JSONObject(result);
								if(! AllResults.get("response").equals("fail")){
									JSONArray jsonArray = AllResults.getJSONArray("response");
									for (int i =0 ; i< jsonArray.length(); i++){
										JSONObject item = jsonArray.getJSONObject(i);
										final String[] pictureString = MissionTag.ProcessToAdapterByJson(context_this,item, adapter);
										
										 
										//图片下载 部分。。。
										if (pictureString[0] != null && ! pictureString[0].equals("null")){
											try {
												/*
												 * important arguments include:
												 * pictureString[] { picture_info ,mission_object_id, mission_up_email,time_s }
												 */
												new BitmapHelper(context_this).BitmapLoader(pictureString[0],pictureString[3], pictureString[2],pictureString[1],new  onBitmapLoaded(){
	
													@Override
													public void onLoadByWeb(byte[] data) {
														// TODO Auto-generated method stub
														Bitmap bitmap  = BitmapFactory.decodeByteArray(data, 0, data.length); 
														String pathPic = BitmapHelper.SaveImage(pictureString[1],data);
														ContentValues values = new ContentValues();
														values.put(TempDataBase.PICTURE, pathPic);
														if(pictureString[1]!= null){
															new TempDataBase(context_this).UpdateByOid(pictureString[1],TempDataBase.PICTURE, pathPic);
														}
														/*
														if(new MissionDataBase(context_this).SearcherByEmailAndTime(pictureString[2], pictureString[3], MissionDataBase.MISS_OBJ_ID).equals(pictureString[1])){
															Log.d("CACHE", "found in DB");
														}else {
															Log.d("CACHE", "not found in DB");
														}
														*/
														adapter.addBitMapData(pictureString[1],bitmap);
													}
	
													@Override
													public void onLoadByLocal( String uri) {
														// TODO Auto-generated method stub
														File file = new File(uri);
														if(file.exists()){
															Log.d("CACHE","This file exist :"+file.getPath());
														}
														Bitmap my_image = BitmapFactory.decodeFile(uri);
														adapter.addBitMapData(pictureString[1], my_image);
														
													}
													
												});
											} catch (IOException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											}
											/*
											BitmapDownloader.Download(context_this, pictureString[0], new CallBack(){
		
												@Override
												public void onDataGot(byte[] data) {
													// TODO Auto-generated method stub
													Bitmap bitmap  = BitmapFactory.decodeByteArray(data, 0, data.length); 
													String pathPic = BitmapHelper.SaveImage(pictureString[1],data);
													ContentValues values = new ContentValues();
													values.put(MissionDataBase.PICTURE, pathPic);
													new MissionDataBase(context_this).UpdateByOid(pictureString[1], values);
													adapter.addBitMapData(pictureString[1],bitmap);
												}
												
											});
											*/
										}else{
											Toast.makeText(context_this, "no picture update!s", Toast.LENGTH_SHORT).show();
										}
									}
								}
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
							TaskList.onRefreshComplete();
						}

						@Override
						public void Failed() {
							// TODO Auto-generated method stub
							
						}

					
				});
			
				return DragListView.DONE;
			}
			
			
		});
		TaskList.setOnRefreshTailListener(new OnRefreshTailListener() {
			
			@Override
			public int onRefresh() {
				// TODO Auto-generated method stub
				return DragListView.UP_DONE;
			}
		});
		TaskList.onRefreshDoSomeThing();
		TaskList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long arg3) {
				Intent intent = new Intent(IndexFullscreenActivity.this,IfRecieveDialog.class);
				Log.d("CACHE", "index : "+String.valueOf(position));
				String obj  = adapter.getObjIds().get(position-1);
				Personal_Info_database db = new Personal_Info_database(context_this);
				String up_email = db.searchEmail(uid);
				intent.putExtra("mission_id",obj );
				intent.putExtra("up_email", up_email);
				intent.putExtra("uid", uid);
				intent.putExtra("token_id", token_id);
				intent.putExtra("token_key", token_key);
				db.close();
				IndexFullscreenActivity.this.startActivity(intent);
				
			}
		
		});
	}
	 
	
	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		// Trigger the initial hide() shortly after the activity has been
		// created, to briefly hint to the user that UI controls
		// are available.
		delayedHide(100);
	}

	/**
	 * Touch listener to use for in-layout UI controls to delay hiding the
	 * system UI. This is to prevent the jarring behavior of controls going away
	 * while interacting with activity UI.
	 */
	View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			if (AUTO_HIDE) {
				delayedHide(AUTO_HIDE_DELAY_MILLIS);
			}
			return false;
		}
	};

	Handler mHideHandler = new Handler();
	Runnable mHideRunnable = new Runnable() {
		@Override
		public void run() {
			mSystemUiHider.hide();
		}
	};

	/**
	 * Schedules a call to hide() in [delay] milliseconds, canceling any
	 * previously scheduled calls.
	 */
	private void delayedHide(int delayMillis) {
		mHideHandler.removeCallbacks(mHideRunnable);
		mHideHandler.postDelayed(mHideRunnable, delayMillis);
	}
	
	/*
	 * 
	 * Some methods to implement kinds of task
	 */
	
	public void turn_mission_activity_listener(View view){
		Intent intent = new Intent(IndexFullscreenActivity.this,
				MissionListFullscreenActivity.class);
		Log.d("My_signal","activity:"+TAG +"uid :"+uid);
		intent.putExtra("uid",uid );
		intent.putExtra("token_id", token_id);
		intent.putExtra("token_key", token_key);
		Log.d(tag, token_id+" key : "+token_key);
		IndexFullscreenActivity.this.startActivity(intent);
		
	}
	public void turn_missSign_activity_listener(View view){
		Intent intent = new Intent(IndexFullscreenActivity.this,
				MissionSignFullscreenActivity.class);
		intent.putExtra("uid",uid );
		intent.putExtra("token_id", token_id);
		intent.putExtra("token_key", token_key);
		IndexFullscreenActivity.this.startActivity(intent);
		
	}
	public void Map_model (View view){
		Intent intent = new Intent(IndexFullscreenActivity.this,
				MapModel.class);
		intent.putExtra("uid",uid );
		intent.putExtra("token_id", token_id);
		intent.putExtra("token_key", token_key);
		IndexFullscreenActivity.this.startActivity(intent);
		
	}
}
